// pages/rewardList/rewardList.js
import sweepstakeApi from '../../service/sweepstakeApi'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    rewardList: [],
    page: {
      start: 1,
      size: 5,
      nextFlag: false
    },
    showLoadMore: true,
    loadMoreFlag: false,
    loadMoreText: '加载中...'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.checkStatus()
    this.getRewardList(true)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  getRewardList (refreshFlag) {
    let that = this
    that.setLoadMoreStatus('loading')
    sweepstakeApi.getRewardList({
      startPage: that.data.page.start + '',
      pageSize: that.data.page.size + ''
    }).then((res) => {
      wx.stopPullDownRefresh()
      that.setData({
        loadMoreFlag: false
      })
      if (app.globalData.codeConfig.errCode.SUCCESS_CODE === res.data.errCode) {
        let data = res.data.data
        that.setData({
          rewardList: refreshFlag ? [...data.winners] : [...that.data.rewardList, ...data.winners],
          page: {...data.page}
        })
        if (that.data.page.nextFlag) {
          that.setLoadMoreStatus('has-next')
        } else {
          that.setLoadMoreStatus('no-more')
        }
      }
    }).catch((res) => {
      wx.stopPullDownRefresh()
      if (that.data.page.nextFlag) {
        that.setLoadMoreStatus('has-next')
      } else {
        that.setLoadMoreStatus('no-more')
      }
    })
  },
  handleLoadMore () {
    let that = this
    if (!that.data.page.nextFlag) return
    that.setData({
      ['page.start']: (that.data.page.start - 0) + 1
    })
    that.getRewardList(false)
  },
  setLoadMoreStatus (status) {
    if (status === 'has-next') {
      this.setData({
        loadMoreFlag: false,
        showLoadMore: true,
        loadMoreText: '加载更多'
      })
    } else if (status === 'loading') {
      this.setData({
        loadMoreFlag: true,
        showLoadMore: true,
        loadMoreText: '加载中...'
      })
    } else if (status === 'no-more') {
      this.setData({
        loadMoreFlag: false,
        showLoadMore: this.data.rewardList.length > 5 ? true : false,
        loadMoreText: '没有更多数据啦'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getRewardList(true)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})